using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace SpellCenter.UI
{
    internal class ContextDisplayColumnPM
    {
        private static readonly Regex s_whitespaceRegex = new Regex(
                @"^\s*(?<content>.*?)\s*$", RegexOptions.Compiled);
        public static string[] StripLeadingAndTrailingWhitespaces(string[] strings)
        {
            for (int i = 0; i < strings.Length; i++)
            {
                strings[i] = ChopSpaces(strings[i]);
            }
            return strings;
        }

        private static string ChopSpaces(string s)
        {
            Match match = s_whitespaceRegex.Match(s);
            return match.Groups["content"].Value;
        }

        private static readonly string s_ellipsis = "...";
        public static string GetFrontalEllipsisString(Rectangle rect0, string s, Font font)
        {
            int textWidth = TextRenderer.MeasureText(s, font).Width;
            if (textWidth > rect0.Width)
            {
                int allowedWidth = rect0.Width - TextRenderer.MeasureText(s_ellipsis, font).Width;
//                StringBuilder sb = new StringBuilder(s);
                string result = ShortenStringToFitAllowedWidth(s, font, textWidth, allowedWidth);

                return s_ellipsis + result;
            }
            else return s;
        }

        public static string ShortenStringToFitAllowedWidth(string s, Font font, int textWidth, int allowedWidth)
        {
            string result = s;

            float shrinkRatio = allowedWidth / (float)textWidth;
            int stringLength = (int)(result.Length * shrinkRatio);
            result = result.Substring(result.Length - stringLength);
            textWidth = TextRenderer.MeasureText(result, font).Width;

            if (textWidth > allowedWidth && result.Length > 1)
            {   // if it still doesn't fit, take one more character off
                result = result.Substring(1);
            }
            return result;
        }
    }
}
